// components/calendar/calendar.js
const dayjs = require("./dayjs")
Component({
  /**
   * 组件的属性列表
   */

  properties: {
    //底下需要展示小圆点的日期数组
    spot: {
      type: Array,
      value: []
    },
    leave: {
      type: Array,
      value: []
    },
    Supplementary: {
      type: Array,
      value: []
    },
    absence: {
      type: Array,
      value: []
    },
    //组件渲染时默认选中的时间
    defaultDate: {
      type: String,
      optionalTypes: [Date, Number],
      value: ''
    }
  },
  lifetimes: {
    attached: function () {
      let now = new Date();
      let year = now.getFullYear();
      let month = now.getMonth() + 1;
      this.data.nowDay = '' + year + '-' + month + '-' + now.getDate()
      this.data.nowYear = year
      this.data.nowMonth = month
      this.dateInit();
      this.setData({
        year: year,
        month: month,
        dateString: '' + year + '-' + month + '-' + now.getDate()
      })
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    dateList: [], //日历主体渲染数组
    selectDay: {}, //选中时间
    open: true, //日历是否展开
    transform: 0, //收起时日历高度偏移倍数
    show:true,


    year: 0,
    month: 0,
    // date: ['日', '一', '二', '三', '四', '五', '六'],
    dateList: [],
    dateString: 0,
    nowDay: "",  // 今天的时间
    nowDayIndex: "",  // 今天的时间的索引,
    selsecDay: [],// 选中的时间集合
    nowYear: "",
    nowMonth: "",
    itemlist:[
      {
        data:'2022-06-17'
      },
      {
        data:'2022-06-17'
      },
      {
        data:'2022-06-17'
      }
    ],
  },
  

  /**
   * 组件的方法列表
   */
  methods: {
    //删除事件
    del: function (e) {
      this.data.itemlist.splice(e.currentTarget.dataset.index, 1)
      this.setData({
        itemlist: this.data.itemlist
      })
    },
    click:function(){
      if(this.data.show){
        this.setData({
          hidden:false,
          hidden1:true,
          show:false
        })
      }else{
        this.setData({
          hidden:true,
          hidden1:false,
          show:true
        })
      }
    },
    //picker设置月份
    editMonth(e) {
      const arr = e.detail.value.split("-")
      this.setDate(parseInt(arr[0]), parseInt(arr[1]) - 1)
    },
    //上月切换按钮点击
    lastMonth() {
      const lastMonth = dayjs(new Date(this.data.selectDay.year, this.data.selectDay.month - 1))
      this.setDate(lastMonth.year(), lastMonth.month())
    },
    //下月切换按钮点击
    nextMonth() {
      const nextMonth = dayjs(new Date(this.data.selectDay.year, this.data.selectDay.month + 1))
      this.setDate(nextMonth.year(), nextMonth.month())
    },
    //设置选中日期
    setDate(paramYear, paramMonth, paramDate) {
      const date = Math.min(dayjs(`${paramYear}-${paramMonth + 1}`).daysInMonth(), this.data.selectDay.date)
      const time = dayjs(`${paramYear}-${paramMonth + 1}-${paramDate || date}`)
      const selectDay = {
        year: paramYear,
        month: paramMonth,
        date: paramDate || date,
        dateString: time.format("YYYY-MM-DD"),
      }
      //设置收起时的日历主体偏移量
      let dateListStart = dayjs(`${paramYear}-${paramMonth + 1}`).day(0)
      this.setData({
        transform: dayjs(`${paramYear}-${paramMonth + 1}-${paramDate || date}`).day(0).diff(dateListStart, 'week')
      })
      if (paramYear !== this.data.selectDay.year) {
        this.setData({
          selectDay
        })
        this.dateListInit(paramYear, paramMonth)
        this.triggerEvent("dateChange", this.data.selectDay)
        this.triggerEvent("monthChange", this.data.selectDay)
        this.triggerEvent("yearChange", this.data.selectDay)
        return
      }
      if (paramMonth !== this.data.selectDay.month) {
        this.setData({
          selectDay,
          open: true
        })
        this.dateListInit(paramYear, paramMonth)
        this.triggerEvent("dateChange", this.data.selectDay)
        this.triggerEvent("monthChange", this.data.selectDay)
        return
      }
      if (paramDate && paramDate !== this.data.selectDay.date) {
        this.setData({
          selectDay
        })
        this.triggerEvent("dateChange", this.data.selectDay)
      }

    },

    //展开收起
    openChange() {
      this.setData({
        open: !this.data.open
      })
    },

    //日历主体的渲染方法
    dateListInit(paramYear = this.data.selectDay.year, paramMonth = this.data.selectDay.month) {
      let dateList = []; //需要遍历的日历数组数据
      let startDate = dayjs(`${paramYear}-${paramMonth + 1}`).day(0) //日历渲染开始日期
      let endDate = dayjs(`${paramYear}-${paramMonth + 1}`).endOf('month').day(6) //日历主体渲染结束日期
      const timeArr = this.data.spot.map(item => {
        return dayjs(item).format('YYYY-MM-DD')
      })
      const leave = this.data.leave.map(item => {
        return dayjs(item).format('YYYY-MM-DD')
      })
      const Supplementary = this.data.Supplementary.map(item => {
        return dayjs(item).format('YYYY-MM-DD')
      })
      const absence = this.data.absence.map(item => {
        return dayjs(item).format('YYYY-MM-DD')
      }) //底部小圆点需要展示的数组
      while (startDate < endDate) {
        const dateString = startDate.format("YYYY-MM-DD")
        dateList.push({
          date: startDate.date(),
          month: startDate.month(),
          year: startDate.year(),
          dateString,
          spot: timeArr.indexOf(dateString) !== -1,
          leave: leave.indexOf(dateString) !== -1,
          Supplementary: Supplementary.indexOf(dateString) !== -1,
          absence: absence.indexOf(dateString) !== -1
        })
        startDate = startDate.add(1, 'day')
      }
      this.setData({
        dateList: dateList
      })
    },

    //某一天被点击时
    selectChange(e) {
      const year = e.currentTarget.dataset.year
      const month = e.currentTarget.dataset.month
      const date = e.currentTarget.dataset.date
      this.setDate(year, month, date)
    },

    toDate(e) {
      let date = e.currentTarget.dataset.date
      let clickYear = e.currentTarget.dataset.year
      // this.setData({
      //   isToday: date
      // })
      // 如果为选中过就添加的selsecDay
      let dateList = this.data.dateList
      let year = this.data.nowYear
      let month = this.data.nowMonth
      let nowDayIndex = this.data.nowDayIndex
      let selsecDay = this.data.selsecDay
      for(let i = 0;i<selsecDay.length;i++){
        let els = selsecDay[i]
        if(els.year == clickYear && els.isToday == date){
          selsecDay.splice(i,1)
          this.data.selsecDay = selsecDay
          dateList.forEach((el,ins)=>{
            if(el.year == clickYear && el.isToday == date){
              el.is_select = false
              this.setData({
                dateList:dateList
              })
            }
          })
          return 
        }
      }
      console.log(this.data.selsecDay)
      console.log(dateList)
      // console.log(year)
      // console.log(month)
      // console.log(nowDayIndex)
      for (let i = 0; i < dateList.length; i++) {
        // 判断年份大小
        // console.log(i)
        let el = dateList[i];
        if (el.year < year) {  
          return console.log("选择年份较小")
        } else if (el.year == year && el.month < month) {
          return console.log("选择月份较小")
        } else if (el.year == year && el.month == month && date == el.isToday) {
          console.log(i)
          if(i >= nowDayIndex){
           this.add(el)
          }else{
            return console.log("选择大于当天")
          }
        } else if((el.year = year ||el.year > year) && el.month > month && date == el.isToday){
          this.add(el)
        }
      }
    },
    // 存储时间
    add(date){
      let is = true // 是否存入数据
      let selsecDay = this.data.selsecDay
      for (let i = 0; i < selsecDay.length; i++) {
        let el = selsecDay[i];
        if(el.isToday == date.isToday && el.year == date.year){ // 年份月份相同不可存入
          is = false
        }
        
      }
      if(is){
        this.data.selsecDay.push(date)
      }
      this.screen()
      // console.log(this.data.selsecDay)
    },
    // 筛选选中的条件
    screen(){
      let selsecDay = this.data.selsecDay
      let dateList = this.data.dateList
      dateList.forEach((el,i)=>{
        selsecDay.forEach((els,ins)=>{
          if(el.isToday == els.isToday && el.year == els.year){
            el.is_select = true
          }
        })
      })
      this.setData({
        dateList:dateList
      })
      // console.log(dateList)
    },
    dateInit: function (setYear, setMonth) {
      //全部时间的月份都是按0~11基准，显示月份才+1
      let dateList = [];                        //需要遍历的日历数组数据
      let arrLen = 0;                            //dateList的数组长度
      let now = setYear ? new Date(setYear, setMonth) : new Date();
      let year = setYear || now.getFullYear();
      let nextYear = 0;
      let month = setMonth || now.getMonth();                    //没有+1方便后面计算当月总天数
      let nextMonth = (month + 1) > 11 ? 1 : (month + 1);
      let startWeek = new Date(year + '/' + (month + 1) + '/' + 1).getDay();                            //目标月1号对应的星期
      let dayNums = new Date(year, nextMonth, 0).getDate();                //获取目标月有多少天
      let obj = {};
      let num = 0;
      if (month + 1 > 11) {
        nextYear = year + 1;
        dayNums = new Date(nextYear, nextMonth, 0).getDate();
      }
      arrLen = startWeek + dayNums;
      for (let i = 0; i < arrLen; i++) {

        if (i >= startWeek) {
          num = i - startWeek + 1;
          obj = {
            isToday: '' + year + '-' + (month + 1) + '-' + num,
            dateNum: num,
            weight: 5,
            is_select: false,
            year: year,
            month: month + 1
          }
          if (this.data.nowDay == obj.isToday) {
            // obj.is_select = true
            this.data.nowDayIndex = i  // 记录当天的索引位置 用于判断选择时不选择逼当前月小的
          }
        } else {
          obj = {};
        }
        dateList[i] = obj;
      }
      console.log(dateList)
      this.setData({
        dateList: dateList
      })
      let nowDate = new Date();
      let nowYear = nowDate.getFullYear();
      let nowMonth = nowDate.getMonth() + 1;
      let nowWeek = nowDate.getDay();
      let getYear = setYear || nowYear;
      let getMonth = setMonth >= 0 ? (setMonth + 1) : nowMonth;
      if (nowYear == getYear && nowMonth == getMonth) {
        this.setData({
          isTodayWeek: true,
          todayIndex: nowWeek
        })
      } else {
        this.setData({
          isTodayWeek: false,
          todayIndex: -1
        })
      }
    },
  },
  //组件生命周期
  lifetimes: {
    attached() {
      let now = this.data.defaultDate ? dayjs(this.data.defaultDate) : dayjs()
      this.setDate(now.year(), now.month(), now.date())
    }
  },
  //监听参数变化
  observers: {
    spot: function () {
      this.dateListInit()
    }
  }
})